<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { getMenuSelect, add, update } from '@/api/system/menu'
import { notify } from "@/utils/element";

/**
 * 输入规则
 */
const rules = reactive<FormRules>({})

/**
 * 表单ref
 */
const formRef = ref()

/**
 * 表格参数
 */
const formLabelWidth = ref('90px')
const state = reactive({
  title: '新增', // 新增、编辑
  type: 'add' as FormType,
  visible: false,
  loading: false,
  menuList: [], // 存在父菜单下拉选择项
  formData: {
    meta: {},
  } as SysMenuType,
})
const { title, visible, loading, menuList, formData } = { ...toRefs(state) }

// 定义自定义事件
const emit = defineEmits(['refresh'])

// 导出提交给父组件使用
defineExpose({
  open // open: open
});

// 初始数据
const initData = { type: '1', isLink: false, sort: 1, meta: { hidden: false, cache: true, isBreadcrumd: true } };

/**
 * 打开窗口
 * @param data 初始表单数据（新增时parentId传递，编辑时可传递修改的数据）
 */
function open(type: FormType, title: string, data = {} as any) {
  state.type = type;
  state.title = title;
  // 合并初始数据(深度拷贝一份，不然会影响原数据)
  state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
  state.visible = true;
  // 查询所有菜单项
  loadMenuSelect();
}

/**
 * 查询所有菜单(不加载按钮)
 */
async function loadMenuSelect() {
  try {
    const { data } = await getMenuSelect();
    state.menuList = data;
  } catch (error) {
  } finally {
  }
}

/**
 * 不是外链：清空linkTo外链地址
 * @param val 链接
 */
function changeIsLink(val: boolean) {
  if (!val) state.formData.meta.linkTo = '';
}

/**
 * 关闭窗口前触发
 */
function close() {
  if (state.loading) return
  formRef.value?.resetFields()
  state.visible = false
}

/**
 * 取消
 */
const handleCancel = () => {
  close()
}

/**
 * 提交表单
 */
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (state.formData.type == '2') {
        state.formData.path = '';
        state.formData.name = '';
        state.formData.redirect = '';
        state.formData.component = '';
        state.formData.isLink = false;
        state.formData.meta.linkTo = '';
        state.formData.meta.icon = '';
        state.formData.meta.hidden = false;
        state.formData.meta.cache = false;
        state.formData.meta.isBreadcrumd = false;
      }
      // 调用接口提交数据
      submitData()
    }
  })
}

async function submitData() {
  try {
    state.loading = true
    console.log('提交菜单', formData);
    let res: any = {}
    if (state.type === 'edit') {
      // 修改
      res = await update(state.formData)
    } else {
      // 新增
      res = await add(state.formData)
    }
    state.loading = false
    if (res.code !== 20000) return
    notify('操作成功！', { type: 'success' })
    // 关闭窗口
    close();
    // 触发父组件重新加载数据
    emit('refresh');

  } catch (error) {
  } finally {
    close()
    state.loading = false
  }
}
</script>

<template>
  <el-dialog :title="title + '菜单'" v-model="visible" direction="rtl" size="650px" @close="close" draggable>
    <div class="drawer__content">
      <el-form ref="formRef" :rules="rules" :model="formData" :label-width="formLabelWidth" label-position="right"
        status-icon>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级菜单" prop="id">
              <el-cascader v-model="formData.id" :options="menuList" clearable filterable style="width: 400px;"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'title' }" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="formData.type">
                <el-radio value="1" border>菜单</el-radio>
                <el-radio value="2" border>按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="meta.title"
              :rules="{ required: true, message: '请输入菜单名称', trigger: 'blur' }">
              <el-input v-model="formData.meta.title" placeholder="请输入菜单名称" maxlength="50" clearable show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sort">
              <el-input-number v-model="formData.sort" :min="1" :max="10000" style="width:600px" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="formData.type === '2'">
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" placeholder="请输入权限标识" maxlength="50" clearable show-word-limit />
          </el-form-item>
        </template>
        <template v-else>
          <el-row>
            <el-col :span="12">
              <el-form-item label="路由地址" prop="path">
                <el-input v-model="formData.path" placeholder="请输入路由地址path值" maxlength="200" clearable
                  show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路由名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入路由名称相对路径" maxlength="399" clearable show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="菜单图标" prop="meta.icon">
                <el-input v-model="formData.meta.icon" placeholder="请输入图标名" maxlength="100" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重定向" prop="redirect">
                <el-input v-model="formData.redirect" placeholder="请输入路由重定向地址redirect值" maxlength="200" clearable
                  show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否外链" prop="isLink">
                <el-radio-group v-model="formData.isLink" class="ml4" @change="changeIsLink(formData.isLink)">
                  <el-radio :value="false">否</el-radio>
                  <el-radio :value="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示导航" prop="meta.isBreadcrumd">
                <el-radio-group v-model="formData.meta.isBreadcrumd">
                  <el-radio :value="false">不显示</el-radio>
                  <el-radio :value="true">显示</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="formData.isLink">
            <el-form-item label="外链地址" prop="linkTo">
              <el-input v-model="formData.meta.linkTo" placeholder="请输入外链地址" maxlength="300" clearable
                show-word-limit />
            </el-form-item>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否隐藏" prop="hidden"
                :rules="{ required: true, message: '是否隐藏为必选项', trigger: 'change' }">
                <el-radio-group v-model="formData.meta.hidden">
                  <el-radio :value="false">不隐藏</el-radio>
                  <el-radio :value="true">隐藏</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否缓存" prop="cache"
                :rules="{ required: true, message: '是否缓存为必选项', trigger: 'change' }">
                <el-radio-group v-model="formData.meta.cache">
                  <el-radio :value="false">不缓存</el-radio>
                  <el-radio :value="true">缓存</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :autosize="{ minRows: 5 }" placeholder="请输入备注信息"
            maxlength="500" clearable show-word-limit />
        </el-form-item>
        <div class="drawer__footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm(formRef)">
            {{ loading ? '正在提交 ...' : '提 交' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss"></style>